package io.gitee.zhangbinhub.admin.oauth.controller.inner

import cn.dev33.satoken.stp.StpUtil
import io.gitee.zhangbinhub.acp.boot.exceptions.WebException
import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.admin.common.api.CommonPath
import io.gitee.zhangbinhub.admin.common.api.OauthApi
import io.gitee.zhangbinhub.admin.oauth.service.UserService
import io.gitee.zhangbinhub.admin.resource.server.base.BaseResourceServerController
import io.gitee.zhangbinhub.admin.resource.server.vo.UserVo
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.noear.solon.annotation.Controller
import org.noear.solon.annotation.Inject
import org.noear.solon.annotation.Mapping
import org.noear.solon.annotation.Param
import org.noear.solon.core.handle.MethodType
import org.noear.solon.core.util.MimeType
import org.noear.solon.validation.annotation.NotBlank
import org.noear.solon.validation.annotation.Valid

@Valid
@Controller
@Api("用户信息（内部接口）")
open class InnerUserController(
    @Inject logAdapter: LogAdapter,
    private val userService: UserService
) : BaseResourceServerController(logAdapter) {
    @ApiOperation("获取当前用户信息", notes = "根据当前登录的用户token，返回详细信息")
    @Mapping(
        method = [MethodType.GET],
        value = CommonPath.innerBasePath + OauthApi.currUser,
        produces = MimeType.APPLICATION_JSON_VALUE
    )
    @Throws(WebException::class)
    fun currUser(): UserVo =
        userService.getUserInfoByLoginNo(StpUtil.getLoginIdAsString())?.let {
            userService.formatUserVo(it)
        } ?: throw WebException("找不到用户信息")

    @ApiOperation("通过相对机构级别和角色编码，查询用户列表")
    @Mapping(
        method = [MethodType.GET],
        value = CommonPath.innerBasePath + OauthApi.userList,
        produces = MimeType.APPLICATION_JSON_VALUE
    )
    @Throws(WebException::class)
    fun getUserListByRelativeOrgAndRole(
        @ApiParam("机构层级")
        @Param(name = "orgLevel") orgLevel: String?,
        @ApiParam("角色编码", required = true)
        @NotBlank(message = "角色编码不能为空")
        @Param(name = "roleCode") roleCode: String
    ): List<UserVo> = userService.getUserVoListByRelativeOrgAndRole(
        StpUtil.getLoginIdAsString(),
        orgLevel?.split(",")?.map { item -> item.toInt() } ?: listOf(0),
        roleCode.split(",")
    )
}
